package com.huashi.dealer.modular.business.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.Comment;
import com.huashi.dealer.commonEntity.CommentImage;
import com.huashi.dealer.commonEntity.OrderGoods;
import com.huashi.dealer.commonEntity.User;
import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.modular.business.goods.mapper.CommentImageMapper;
import com.huashi.dealer.modular.business.goods.mapper.CommentMapper;

import com.huashi.dealer.modular.business.goods.param.StoreCommentListParam;
import com.huashi.dealer.modular.business.goods.param.StoreCommentUpdateParam;
import com.huashi.dealer.modular.business.goods.service.StoreCommentService;
import com.huashi.dealer.modular.business.goods.vo.StoreCommentListVo;
import com.huashi.dealer.modular.business.goods.vo.StoreCommentDetailVo;
import com.huashi.dealer.modular.business.order.mapper.OrderGoodsMapper;
import com.huashi.dealer.modular.business.upload.mapper.UploadFileMapper;
import com.huashi.dealer.modular.business.user.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Store端商品评论服务实现类
 *
 * @author 谭陈强
 * @since 2025-08-07
 */
@Slf4j
@Service
public class StoreCommentServiceImpl implements StoreCommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private CommentImageMapper commentImageMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderGoodsMapper orderGoodsMapper;

    @Resource
    private UploadFileMapper uploadFileMapper;

    @Override
    public Page<StoreCommentListVo> getCommentList(StoreCommentListParam param, Page<Comment> page) {
        // 构建查询条件
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        
        // 基础条件：未删除的评论
        queryWrapper.eq(Comment::getIsDelete, 0);
        
        // 评分筛选
        if (param.getScore() != null) {
            queryWrapper.eq(Comment::getScore, param.getScore());
        }
        
        // 显示状态筛选
        if (param.getStatus() != null) {
            queryWrapper.eq(Comment::getStatus, param.getStatus());
        }
        
        // 是否有图片筛选
        if (param.getIsPicture() != null) {
            queryWrapper.eq(Comment::getIsPicture, param.getIsPicture() == 1);
        }
        
        // 搜索关键词
        if (StringUtils.hasText(param.getSearch())) {
            queryWrapper.and(wrapper -> wrapper
                .like(Comment::getContent, param.getSearch())
                .or()
                .exists("SELECT 1 FROM user u WHERE u.user_id = comment.user_id AND u.nick_name LIKE '%" + param.getSearch() + "%'")
                .or()
                .exists("SELECT 1 FROM order_goods og WHERE og.order_goods_id = comment.order_goods_id AND og.goods_name LIKE '%" + param.getSearch() + "%'")
            );
        }
        
        // 排序：按排序值升序，创建时间降序
        queryWrapper.orderByAsc(Comment::getSort)
                   .orderByDesc(Comment::getCreateTime);
        
        // 分页查询
        Page<Comment> commentPage = commentMapper.selectPage(page, queryWrapper);
        
        // 转换为VO
        Page<StoreCommentListVo> resultPage = new Page<>();
        BeanUtils.copyProperties(commentPage, resultPage);
        
        List<StoreCommentListVo> voList = commentPage.getRecords().stream()
                .map(this::convertToStoreCommentListVo)
                .collect(Collectors.toList());

        resultPage.setRecords(voList);
        return resultPage;
    }

    @Override
    public StoreCommentDetailVo getCommentDetail(Long commentId) {
        // 查询评论基本信息
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 转换为VO
        StoreCommentDetailVo vo = new StoreCommentDetailVo();
        BeanUtils.copyProperties(comment, vo);
        
        // 查询用户信息
        User user = userMapper.selectById(comment.getUserId());
        if (user != null) {
            StoreCommentDetailVo.UserVo userVo = new StoreCommentDetailVo.UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setNickName(user.getNickName());
            vo.setUser(userVo);
        }
        
        // 查询订单商品信息
        OrderGoods orderGoods = orderGoodsMapper.selectById(comment.getOrderGoodsId());
        if (orderGoods != null) {
            StoreCommentDetailVo.OrderGoodsVo orderGoodsVo = new StoreCommentDetailVo.OrderGoodsVo();
            orderGoodsVo.setGoodsName(orderGoods.getGoodsName());
            
            // 查询商品图片
            if (orderGoods.getImageId() != null) {
                UploadFile uploadFile = uploadFileMapper.selectById(orderGoods.getImageId());
                if (uploadFile != null) {
                    StoreCommentDetailVo.ImageVo imageVo = new StoreCommentDetailVo.ImageVo();
                    imageVo.setImageId(uploadFile.getFileId());
                    imageVo.setFilePath(uploadFile.getFileUrl());
                    orderGoodsVo.setImage(imageVo);
                }
            }
            vo.setOrderGoods(orderGoodsVo);
        }
        
        // 查询评论图片
        LambdaQueryWrapper<CommentImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(CommentImage::getCommentId, commentId)
                   .orderByAsc(CommentImage::getId);
        List<CommentImage> images = commentImageMapper.selectList(imageWrapper);
        
        List<StoreCommentDetailVo.CommentImageVo> imageVos = images.stream()
                .map(image -> {
                    StoreCommentDetailVo.CommentImageVo imageVo = new StoreCommentDetailVo.CommentImageVo();
                    imageVo.setImageId(Long.valueOf(image.getImageId()));
                    
                    // 查询上传文件信息
                    UploadFile uploadFile = uploadFileMapper.selectById(image.getImageId());
                    if (uploadFile != null) {
                        imageVo.setFilePath(uploadFile.getFileUrl());
                        imageVo.setFileName(uploadFile.getFileName());
                    }
                    return imageVo;
                })
                .collect(Collectors.toList());
        vo.setImages(imageVos);
        
        // 设置创建时间
        if (comment.getCreateTime() != null) {
            vo.setCreateTime(LocalDateTime.ofEpochSecond(comment.getCreateTime(), 0, ZoneOffset.ofHours(8)));
        }
        
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateComment(StoreCommentUpdateParam param) {
        // 验证评论是否存在
        Comment comment = commentMapper.selectById(param.getCommentId());
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 更新评论基本信息
        Comment updateComment = new Comment();
        updateComment.setCommentId(param.getCommentId());
        updateComment.setScore(param.getScore());
        updateComment.setContent(param.getContent());
        updateComment.setStatus(param.getStatus());
        updateComment.setSort(param.getSort());
        
        commentMapper.updateById(updateComment);
        
        // 更新评论图片
        if (param.getImages() != null) {
            updateCommentImages(param.getImages(), param.getCommentId());
        }
        
        // 更新是否有图片标识
        LambdaQueryWrapper<CommentImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(CommentImage::getCommentId, param.getCommentId());
        long imageCount = commentImageMapper.selectCount(imageWrapper);
        
        LambdaUpdateWrapper<Comment> isPictureWrapper = new LambdaUpdateWrapper<>();
        isPictureWrapper.eq(Comment::getCommentId, param.getCommentId())
                       .set(Comment::getIsPicture, imageCount > 0);
        commentMapper.update(null, isPictureWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long commentId) {
        // 软删除
        LambdaUpdateWrapper<Comment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Comment::getCommentId, commentId)
                    .set(Comment::getIsDelete, 1);

        int result = commentMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("评论不存在或删除失败");
        }
    }

    /**
     * 更新评论图片
     */
    private void updateCommentImages(List<Long> imageIds, Long commentId) {
        // 1. 删除现有图片
        LambdaQueryWrapper<CommentImage> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(CommentImage::getCommentId, commentId);
        commentImageMapper.delete(deleteWrapper);

        // 2. 添加新图片
        if (CollUtil.isNotEmpty(imageIds)) {
            for (Long imageId : imageIds) {
                CommentImage commentImage = new CommentImage();
                commentImage.setCommentId(commentId);
                commentImage.setImageId(imageId.intValue());
                commentImageMapper.insert(commentImage);
            }
        }
    }

    /**
     * 转换为StoreCommentListVo
     */
    private StoreCommentListVo convertToStoreCommentListVo(Comment comment) {
        StoreCommentListVo vo = new StoreCommentListVo();
        BeanUtils.copyProperties(comment, vo);
        
        // 设置创建时间
        if (comment.getCreateTime() != null) {
            vo.setCreateTime(LocalDateTime.ofEpochSecond(comment.getCreateTime(), 0, ZoneOffset.ofHours(8)));
        }
        
        // 设置评分
        StoreCommentListVo.ScoreVo scoreVo = new StoreCommentListVo.ScoreVo();
        scoreVo.setValue(comment.getScore());
        switch (comment.getScore()) {
            case 10:
                scoreVo.setText("好评");
                break;
            case 20:
                scoreVo.setText("中评");
                break;
            case 30:
                scoreVo.setText("差评");
                break;
            default:
                scoreVo.setText("未知");
        }
        vo.setScore(scoreVo);
        
        // 设置显示状态
        StoreCommentListVo.StatusVo statusVo = new StoreCommentListVo.StatusVo();
        statusVo.setValue(comment.getStatus());
        statusVo.setText(comment.getStatus() == 1 ? "显示" : "隐藏");
        vo.setStatus(statusVo);
        
        // 查询用户信息
        User user = userMapper.selectById(comment.getUserId());
        if (user != null) {
            StoreCommentListVo.UserVo userVo = new StoreCommentListVo.UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setNickName(user.getNickName());
            vo.setUser(userVo);
        }
        
        // 查询订单商品信息
        OrderGoods orderGoods = orderGoodsMapper.selectById(comment.getOrderGoodsId());
        if (orderGoods != null) {
            StoreCommentListVo.OrderGoodsVo orderGoodsVo = new StoreCommentListVo.OrderGoodsVo();
            orderGoodsVo.setGoodsName(orderGoods.getGoodsName());
            
            // 查询商品图片
            if (orderGoods.getImageId() != null) {
                UploadFile uploadFile = uploadFileMapper.selectById(orderGoods.getImageId());
                if (uploadFile != null) {
                    StoreCommentListVo.ImageVo imageVo = new StoreCommentListVo.ImageVo();
                    imageVo.setImageId(uploadFile.getFileId());
                    imageVo.setFilePath(uploadFile.getFileUrl());
                    orderGoodsVo.setImage(imageVo);
                }
            }
            vo.setOrderGoods(orderGoodsVo);
        }
        
        return vo;
    }
}
